import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:file_picker/file_picker.dart';
import 'dart:io';
import '../services/api_service.dart';
import '../utils/logger.dart';

/// 通用上传选择器
/// 支持图片和视频上传
class UploadSelector extends StatefulWidget {
  final List<String> urls;
  final Function(List<String>) onUrlsChanged;
  final UploadType uploadType;
  final int maxCount;
  final double itemSize;
  final bool showPreview;

  const UploadSelector({
    super.key,
    required this.urls,
    required this.onUrlsChanged,
    this.uploadType = UploadType.image,
    this.maxCount = 9,
    this.itemSize = 120.0,
    this.showPreview = true,
  });

  @override
  State<UploadSelector> createState() => _UploadSelectorState();
}

class _UploadSelectorState extends State<UploadSelector> {
  bool _isUploading = false;
  int _uploadingCount = 0;

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildHeader(),
        const SizedBox(height: 8),
        _buildUploadGrid(),
        if (_isUploading) _buildUploadProgress(),
      ],
    );
  }

  Widget _buildHeader() {
    return Row(
      children: [
        Text(
          widget.uploadType == UploadType.image ? '选择图片' : '选择视频',
          style: const TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.w600,
            color: Color(0xFF333333),
          ),
        ),
        const Spacer(),
        if (widget.urls.isNotEmpty)
          TextButton(
            onPressed: _clearAll,
            child: const Text(
              '清除全部',
              style: TextStyle(
                color: Color(0xFF999999),
                fontSize: 14,
              ),
            ),
          ),
      ],
    );
  }

  Widget _buildUploadGrid() {
    return Container(
      width: double.infinity,
      height: widget.itemSize,
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        itemCount: widget.urls.length + (widget.urls.length < widget.maxCount ? 1 : 0),
        itemBuilder: (context, index) {
          if (index == widget.urls.length) {
            return _buildAddButton();
          }
          return _buildItem(index);
        },
      ),
    );
  }

  Widget _buildAddButton() {
    return Container(
      width: widget.itemSize,
      height: widget.itemSize,
      margin: const EdgeInsets.only(right: 8),
      decoration: BoxDecoration(
        border: Border.all(
          color: Colors.grey.shade300,
          width: 1,
        ),
        borderRadius: BorderRadius.circular(12),
        color: Colors.grey.shade50,
      ),
      child: InkWell(
        onTap: _isUploading ? null : _showUploadOptions,
        borderRadius: BorderRadius.circular(12),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              widget.uploadType == UploadType.image 
                ? Icons.add_photo_alternate_outlined
                : Icons.video_library_outlined,
              size: 32,
              color: _isUploading ? Colors.grey.shade400 : Colors.grey.shade600,
            ),
            const SizedBox(height: 8),
            Text(
              _isUploading ? '上传中...' : '添加${widget.uploadType == UploadType.image ? '图片' : '视频'}',
              style: TextStyle(
                color: _isUploading ? Colors.grey.shade400 : Colors.grey.shade600,
                fontSize: 12,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildItem(int index) {
    return Container(
      width: widget.itemSize,
      height: widget.itemSize,
      margin: const EdgeInsets.only(right: 8),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.grey.shade300),
      ),
      child: Stack(
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(12),
            child: widget.showPreview
                ? Image.network(
                    widget.urls[index],
                    width: widget.itemSize,
                    height: widget.itemSize,
                    fit: BoxFit.cover,
                    errorBuilder: (context, error, stackTrace) {
                      return Container(
                        width: widget.itemSize,
                        height: widget.itemSize,
                        color: Colors.grey.shade200,
                        child: Icon(
                          widget.uploadType == UploadType.image 
                            ? Icons.image_outlined
                            : Icons.video_file_outlined,
                          color: Colors.grey.shade400,
                        ),
                      );
                    },
                  )
                : Container(
                    width: widget.itemSize,
                    height: widget.itemSize,
                    color: Colors.grey.shade200,
                    child: Icon(
                      widget.uploadType == UploadType.image 
                        ? Icons.image_outlined
                        : Icons.video_file_outlined,
                      color: Colors.grey.shade400,
                    ),
                  ),
          ),
          Positioned(
            top: 4,
            right: 4,
            child: GestureDetector(
              onTap: () => _removeItem(index),
              child: Container(
                padding: const EdgeInsets.all(4),
                decoration: BoxDecoration(
                  color: Colors.red.withOpacity(0.8),
                  shape: BoxShape.circle,
                ),
                child: const Icon(
                  Icons.close,
                  color: Colors.white,
                  size: 16,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildUploadProgress() {
    return Container(
      margin: const EdgeInsets.only(top: 8),
      child: Row(
        children: [
          const SizedBox(
            width: 16,
            height: 16,
            child: CircularProgressIndicator(strokeWidth: 2),
          ),
          const SizedBox(width: 8),
          Text(
            '正在上传 $_uploadingCount 个文件...',
            style: TextStyle(
              color: Colors.grey.shade600,
              fontSize: 12,
            ),
          ),
        ],
      ),
    );
  }

  void _showUploadOptions() {
    showModalBottomSheet(
      context: context,
      builder: (context) => Container(
        padding: const EdgeInsets.all(16),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            if (widget.uploadType == UploadType.image) ...[
              ListTile(
                leading: const Icon(Icons.camera_alt),
                title: const Text('拍照'),
                onTap: () {
                  Navigator.pop(context);
                  _pickFromCamera();
                },
              ),
              ListTile(
                leading: const Icon(Icons.photo_library),
                title: const Text('从相册选择'),
                onTap: () {
                  Navigator.pop(context);
                  _pickFromGallery();
                },
              ),
            ] else ...[
              ListTile(
                leading: const Icon(Icons.video_library),
                title: const Text('选择视频文件'),
                onTap: () {
                  Navigator.pop(context);
                  _pickVideoFile();
                },
              ),
            ],
          ],
        ),
      ),
    );
  }

  Future<void> _pickFromCamera() async {
    try {
      final ImagePicker picker = ImagePicker();
      final XFile? image = await picker.pickImage(
        source: ImageSource.camera,
        maxWidth: 1920,
        maxHeight: 1080,
        imageQuality: 85,
      );
      
      if (image != null) {
        await _uploadFile(File(image.path));
      }
    } catch (e) {
      _showError('拍照失败: $e');
    }
  }

  Future<void> _pickFromGallery() async {
    try {
      final ImagePicker picker = ImagePicker();
      final List<XFile> images = await picker.pickMultiImage(
        maxWidth: 1920,
        maxHeight: 1080,
        imageQuality: 85,
      );
      
      if (images.isNotEmpty) {
        await _uploadFiles(images.map((image) => File(image.path)).toList());
      }
    } catch (e) {
      _showError('选择图片失败: $e');
    }
  }

  Future<void> _pickVideoFile() async {
    try {
      FilePickerResult? result = await FilePicker.platform.pickFiles(
        type: FileType.video,
        allowMultiple: true,
      );

      if (result != null && result.files.isNotEmpty) {
        List<File> files = result.files
            .where((file) => file.path != null)
            .map((file) => File(file.path!))
            .toList();
        
        if (files.isNotEmpty) {
          await _uploadFiles(files);
        }
      }
    } catch (e) {
      _showError('选择视频失败: $e');
    }
  }

  Future<void> _uploadFile(File file) async {
    if (widget.urls.length >= widget.maxCount) {
      _showError('最多只能上传${widget.maxCount}个文件');
      return;
    }

    setState(() {
      _isUploading = true;
      _uploadingCount = 1;
    });

    try {
      String url;
      if (widget.uploadType == UploadType.image) {
        // 上传图片到七牛云
        final result = await ApiService().uploadPostImage(file);
        url = result['data'];
      } else {
        // 上传视频到MinIO
        final result = await ApiService().uploadVideo(file);
        url = result['data'];
      }

      setState(() {
        widget.urls.add(url);
      });
      widget.onUrlsChanged(widget.urls);
      
      _showSuccess('上传成功');
    } catch (e) {
      _showError('上传失败: $e');
    } finally {
      setState(() {
        _isUploading = false;
        _uploadingCount = 0;
      });
    }
  }

  Future<void> _uploadFiles(List<File> files) async {
    if (widget.urls.length + files.length > widget.maxCount) {
      _showError('最多只能上传${widget.maxCount}个文件');
      return;
    }

    setState(() {
      _isUploading = true;
      _uploadingCount = files.length;
    });

    try {
      List<String> urls = [];
      
      if (widget.uploadType == UploadType.image) {
        // 批量上传图片到七牛云
        final result = await ApiService().batchUploadPostImages(files);
        urls = List<String>.from(result['data']);
      } else {
        // 批量上传视频到MinIO
        final result = await ApiService().batchUploadVideos(files);
        urls = List<String>.from(result['data']);
      }

      setState(() {
        widget.urls.addAll(urls);
      });
      widget.onUrlsChanged(widget.urls);
      
      _showSuccess('批量上传成功');
    } catch (e) {
      _showError('批量上传失败: $e');
    } finally {
      setState(() {
        _isUploading = false;
        _uploadingCount = 0;
      });
    }
  }

  void _removeItem(int index) {
    setState(() {
      widget.urls.removeAt(index);
    });
    widget.onUrlsChanged(widget.urls);
  }

  void _clearAll() {
    setState(() {
      widget.urls.clear();
    });
    widget.onUrlsChanged(widget.urls);
  }

  void _showError(String message) {
    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(message),
          backgroundColor: Colors.red,
        ),
      );
    }
  }

  void _showSuccess(String message) {
    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(message),
          backgroundColor: Colors.green,
        ),
      );
    }
  }
}

/// 上传类型枚举
enum UploadType {
  image,
  video,
}
